let app = getApp();
var base64 = require('../../utils/base64.js');
Page({
  /** 
   * 页面的初始数据
   */
  data: {
    glistAll: [],//所购商品信息
    glist: [],
    address: [],//收货地址信息
    active: 'active',
    active2: 'active2',
	active3: 'active3',
    product_id: '',//购物车id
    shop_id: "",//店铺id
	goods_id: "",//商品id
	goods_num: 0,//购物数量
    user_address_default: 0,//是否存在默认地址
    address_id: '',//地址id
	is_allow_visit: 0,
	is_allow_card_pay: 0,
    k: '',
    u: '',
    user_address_contact: '',//收货人姓名
    user_address_phone: '',//收货人电话
    user_address_area: '',//收货人地点
    user_address_address: '',//收货人详细地址
    pay_way: 1,//支付方式 1在线支付 2货到付款
    liuyan: "",
    is_show_time: 1,
    hd: 'pay_add',
    count_price: '',//合计金额
	user_money: '',//用户余额
	user_recharge_card: 0,//用户卡余额
    is_add: false,
    is_discount: 0,//否开启会员折扣 1-开启会员折扣 0-关闭会员折扣
    switch1Checked: false,
    voucher_id: [],//店铺代金券
    redpacket_id: 0,//平台红包
    delivery: 'submit',
    disabled:false,
	virtual_phone: '', // 接收短信的手机号
	date: '',
	startDate: '2025-01-01 00:00',
	endDate: '2055-01-01 00:00',
	minDate: '',
	realDate: '',
	placeholder: '请选择预约时间'
  },
  getNowDate() {
        const now = new Date(); // 获取当前时间对象
        const year = now.getFullYear(); // 年
        const month = now.getMonth() + 1; // 月（+1是因为getMonth()返回0-11）
        const day = now.getDate() + 1; // 日
        this.setData({
          startDate: `${year}-${month}-${day} 09:00`
        });
      },
   // 手机号输入
    bindVirtualPhoneInput: function(e) {
      this.setData({ virtual_phone: e.detail.value });
    },
 onPickerChange: function (e) {
	 const selectedDate = e.detail.dateString; // 假设e.detail.date是选中的日期对象或时间戳
	 // 判断 selectedDate 是否在允许的时间段
	 if (this.isValidTime(selectedDate)) {
	   // 有效，更新
	   this.setData({
	     realDate: selectedDate 	//选中的数据
	   })
	 } else {
	   // 无效，提示并重置为原来的currentDate
	   
	   wx.showModal({
	       title: '提示',
	       content: '请选择明天或以后的日期，且时间在上午9点~12点或下午14点~17点',
	       confirmText: '取消',
	       cancelText: '确定',
	       success(res) {
	       }
	     })
	}	   
 },
 isValidTime: function(date) {
         // 首先，判断日期不能是今天及之前（实际上startDate已经限制为明天开始，所以可以不用判断，但为了安全也可以判断）
         const today = new Date();
         today.setHours(0,0,0,0);
         const selectedDay = new Date(date);
         if (selectedDay <= today) {
           return false;
         }
         // 判断时间是否在9:00-12:00或14:00-17:00
         const hour = selectedDay.getHours();
         const minute = selectedDay.getMinutes();
         const totalMinutes = hour * 60 + minute;
         // 上午9:00到12:00（12:00不算，一般选择器的时间是0点到11:59，但这里我们假设是到12:00整也算，具体根据需求）
         // 假设包括9:00到12:00（包括12:00整）和14:00到17:00（包括17:00整）
         if ((totalMinutes >= 9*60 && totalMinutes <= 12*60) || (totalMinutes >= 14*60 && totalMinutes <= 17*60)) {
           return true;
         }
         return false;
       },
 toDouble: function (num) {
   if (num >= 10) {//大于10
     return num;
   } else {//0-9
     return '0' + num
   }
   },
  getToday: function () {
   let date = new Date();
   let year = date.getFullYear();
   let month = date.getMonth() + 1;
   let day = date.getDate() + 1;
   return year + '-' + this.toDouble(month) + '-' + this.toDouble(day)
   },

  /**
   * 生命周期函数--监听页面加载
   */
// 在 onLoad 函数中，找到处理商品数量的部分，修改如下：
onLoad: function (options) {
  var that = this
  
  // 判断是否从商品详情直接购买
  var fromProductDetail = options.from === 'detail' || !options.product_id;

  this.getNowDate();
  let dayTime = that.getToday();
  let dayHour = "09:00";
  let endedTime1 = dayTime + " " + dayHour;
  that.setData({
    date: endedTime1,
    minDate: endedTime1,
    fromProductDetail: fromProductDetail  // 保存来源信息到data中
  })

  new app.ToastPannel();
  var product_id = options.product_id
  var address_id = options.address_id
  if (address_id == undefined) {
    address_id = ''
  }
  var user_address_address = options.user_address_address
  var user_address_area = options.user_address_area
  var user_address_contact = options.user_address_contact
  var user_address_default = options.user_address_default
  var user_address_phone = options.user_address_phone
  if (product_id) {
    wx.setStorage({
      key: 'product',
      data: options.product_id
    })
  } else {
    product_id = wx.getStorageSync('product');
  }

  var k = wx.getStorageSync('key');
  var u = wx.getStorageSync('u');

  wx.request({
    url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirm&typ=json',
    method: 'GET',
    data: { k: k, u: u, product_id: product_id, address_id: address_id, ifcart: 1, type_wxapp: 'wxapp' },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      var arr = res.data.data.glist
      var total_count = 0;
      var goods_id = '';
      var goods_num = 0;
      var shop_id = [];
      var voucher_id = [];
      var address = res.data.data.address
      var best_voucher = ''
      var glist = res.data.data
      var redpacket_id = 0
      var is_allow_visit = 0
      
      // 有数据的话，就遍历数据，计算总金额 和 总数量  
      if (arr.length > 0) {
        for (var i in arr) {
          var good_num = arr[i].goods;
          arr[i].icon = false
          arr[i].flag = true;
          arr[i].liuyan = ""
          shop_id.push(arr[i].shop_id)
          for (var s in good_num) {
            // 关键修改：根据来源决定初始数量和计算方式
            if (fromProductDetail) {
              // 从商品详情直接购买，数量强制设为1，重新计算金额
              goods_num = 1;
              good_num[s].goods_num = 1;
              // 重新计算总金额，基于数量1
              total_count += Number(good_num[s].now_price) * 1; // 单价 × 数量1
            } else {
              // 从购物车进入，使用购物车中的实际数量
              goods_num = Number(good_num[s].goods_num);
              total_count += Number(good_num[s].sumprice);
            }
            
            total_count += Number(arr[i].freight)
            
            goods_id = Number(good_num[s].goods_id)
            
            if (good_num[s].goods_base.promotion_type == 'groupbuy') {
              if (good_num[s].goods_id == good_num[s].goods_base.goods_id) {
                good_num[s].flag = false
              }
            } else {
              good_num[s].flag = true
            }
            if(good_num[s].common_base.is_allow_visit == '1'){
              is_allow_visit = 1
            }
          }
          
          // 判断优惠券显示
          if (arr[i].best_voucher.length > 0) {
            arr[i].best_voucher_info = '满' + arr[i].best_voucher[0].limit + '减' + arr[i].best_voucher[0].price
          }
          // 把所商品的优惠券拼成数组
          if (arr[i].best_voucher.length > 0) {
            voucher_id.push(arr[i].best_voucher[0].id)
          } else {
            voucher_id.push('')
          }
        }
        
        if (address_id == '' && address.length > 0) {
          for (var j in address) {
            if (address[j].user_address_default == 1) {
              user_address_default = 1
              address_id = address[j].user_address_id
              user_address_contact = address[j].user_address_contact
              user_address_phone = address[j].user_address_phone
              user_address_area = address[j].user_address_area
              user_address_address = address[j].user_address_address
            }
          }
        }
      }
      
      // 判断红包显示
      if (glist.rpt_info && glist.rpt_info.length > 0) {
        glist.best_rpt_info = '满' + glist.rpt_info[0].limit + '减' + glist.rpt_info[0].price
        redpacket_id = glist.rpt_info[0].id
      }
      
      // 更新数据  
      that.setData({
        glist: glist,
        count_price: total_count.toFixed(2), // 使用重新计算的总金额
        user_money: glist.user_resource.user_money,
        user_recharge_card: glist.user_resource.user_recharge_card,
        is_allow_visit: is_allow_visit,
        glistAll: arr,
        total: total_count,
        product_id: product_id,
        shop_id: shop_id,
        goods_id: goods_id,
        goods_num: goods_num,
        user_address_default: user_address_default,
        address_id: address_id,
        k: k,
        u: u,
        user_address_contact: user_address_contact,
        user_address_phone: user_address_phone,
        user_address_area: user_address_area,
        user_address_address: user_address_address,
        is_show_time: 0,
        voucher_id: voucher_id,
        is_discount: glist.is_discount,
        redpacket_id: redpacket_id
      });
    }
  })
},

// 修改数量操作函数，确保更新 goods_num
/* 减数 */
delCount: function (e) {
  var that = this
  var k = wx.getStorageSync('key');
  var u = wx.getStorageSync('u');
  var e_id = e.target.id.substring(3);
  var arr = this.data.glistAll;
  
  for (var i in arr) {
    var del = arr[i].goods;
    for (var s in del) {
      var jian = del[s]
      if (jian.goods_id == e_id) {
        if (del[s].goods_base.lower_limit && jian.goods_num <= del[s].goods_base.lower_limit){
          that.show('该限时折扣商品最少需购买' + del[s].goods_base.lower_limit +'件')
          return
        }
        if (jian.goods_num <= 1) {
          return;
        } else {
          jian.goods_num -= 1
          
          // 如果是购物车进入，更新购物车数量
          if (!that.data.fromProductDetail) {
            wx.request({
              url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
              method: 'GET',
              data: { k: k, u: u, cart_id: jian.cart_id, num: jian.goods_num, },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
              }
            })
          }
          
          // 重新计算总金额
          var total_count = 0;
          for (var i2 in arr) {
            var good_num2 = arr[i2].goods;
            for (var s2 in good_num2) {
              total_count += Number(good_num2[s2].now_price) * good_num2[s2].goods_num;
              total_count += Number(arr[i2].freight)
            }
          }
          
          that.setData({
            glistAll: arr,
            total: total_count,
            count_price: total_count.toFixed(2),
            goods_num: jian.goods_num // 更新 goods_num
          })
        }
      }
    }
  }
},

/* 加数 */
addCount: function (e) {
  var that = this
  var k = wx.getStorageSync('key');
  var u = wx.getStorageSync('u');
  var e_id = e.target.id.substring(3);
  var arr = this.data.glistAll;
  
  for (var i in arr) {
    var add = arr[i].goods;
    for (var s in add) {
      var jia = add[s]
      if (jia.goods_id == e_id) {
        jia.goods_num = Number(jia.goods_num) + 1
        if (jia.goods_num > jia.goods_base.goods_stock) {
          jia.goods_num = jia.goods_base.goods_stock
          that.show("不可超过商品库存")
        } else {
          // 如果是购物车进入，更新购物车数量
          if (!that.data.fromProductDetail) {
            wx.request({
              url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
              method: 'GET',
              data: {
                k: k,
                u: u,
                cart_id: jia.cart_id,
                num: jia.goods_num,
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
              }
            })
          }
          
          // 重新计算总金额
          var total_count = 0;
          for (var i2 in arr) {
            var good_num2 = arr[i2].goods;
            for (var s2 in good_num2) {
              total_count += Number(good_num2[s2].now_price) * good_num2[s2].goods_num;
              total_count += Number(arr[i2].freight)
            }
          }
          
          that.setData({
            glistAll: arr,
            total: total_count,
            count_price: total_count.toFixed(2),
            goods_num: jia.goods_num // 更新 goods_num
          })
        }
      }
    }
  }
},

/*购物车输入数量*/
goodsNum: function (e) {
  var that = this
  var k = wx.getStorageSync('key');
  var u = wx.getStorageSync('u');
  var e_id = e.target.dataset.id;
  var inputNum = e.detail.value
  var arr = that.data.glistAll;
  
  for (var i in arr) {
    var del = arr[i].goods;
    for (var s in del) {
      var jian = del[s]
      if (jian.goods_id == e_id) {
        if (Number(inputNum) == 0) {
          jian.goods_num = 1;
          that.show("数量不能为0")
        } else if (Number(inputNum) > Number(jian.goods_base.goods_stock)) {
          jian.goods_num = jian.goods_base.goods_stock
          that.show("不可超过商品库存")
        } else {
          jian.goods_num = Number(inputNum)
          
          // 如果是购物车进入，更新购物车数量
          if (!that.data.fromProductDetail) {
            wx.request({
              url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
              method: 'GET',
              data: { k: k, u: u, cart_id: jian.cart_id, num: inputNum, },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
              }
            })
          }
        }
        
        // 重新计算总金额
        var total_count = 0;
        for (var i2 in arr) {
          var good_num2 = arr[i2].goods;
          for (var s2 in good_num2) {
            total_count += Number(good_num2[s2].now_price) * good_num2[s2].goods_num;
            total_count += Number(arr[i2].freight)
          }
        }
        
        that.setData({
          glistAll: arr,
          total: total_count,
          count_price: total_count.toFixed(2),
          goods_num: jian.goods_num // 更新 goods_num
        })
        break;
      }
    }
  }
},

// 在支付函数中，确保使用当前的商品数量
formSubmit: function (e) {
  var that = this
  var arr = that.data.glistAll
  var remarks = []
  var pay_way = that.data.pay_way
  that.setData({
    hd: '',
    delivery: ''
  })

  for (var i in arr) {
    remarks.push(arr[i].liuyan)
  }
  
  if (that.data.virtual_phone == '') {
    that.show("请输入手机号码")
  } else if(that.data.realDate == '' ) {
    that.show("请选择预约时间")
  } else {
    app.show('订单提交中', 'loading');
    
    // 获取当前实际商品数量（从页面显示获取）
    var currentGoodsNum = that.data.goods_num;
    
    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Order&met=addVirtualOrder&typ=json&from=wap',
      method: 'GET',
      data: {
        k: that.data.k,
        u: that.data.u,
        address_id: that.data.address_id,
        receiver_name: that.data.user_address_contact,
        receiver_address: that.data.user_address_area + '' + that.data.user_address_address,
        receiver_phone: that.data.virtual_phone,
        is_allow_visit: that.data.is_allow_visit,
        area_code: "86",
        buyer_phone: that.data.virtual_phone,
        goods_id: that.data.goods_id,
        goods_num: currentGoodsNum, // 使用当前页面显示的数量
        pay_way_id: pay_way,
        remarks: that.data.realDate,
        wxapp: 'wxapp',
        is_discount: that.data.is_discount,
        voucher_id: that.data.voucher_id.toString(),
        redpacket_id: that.data.redpacket_id,
        look_common_packing_list: 1,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.status == 200) {
          // 支付逻辑保持不变...
          if (pay_way == 2) {
            wx.redirectTo({
              url: '../order_list/order_list'
            })
          } else if (pay_way == 3) {
            that.pay_yue(res.data.data.uorder,res.data.data.order_id)
          } else if (pay_way == 4) {
            that.pay_card_yue(res.data.data.uorder,res.data.data.order_id)
          } else {
            that.pay(res.data.data.uorder,res.data.data.order_id)
          }
        } else {
          that.show("支付失败,请重新支付")
        }
      }
    })
  }
},

  //留言
  liuyan: function (e) {
    var that = this
    var arr = that.data.glistAll
    var shop_id = e.target.dataset.id
    for (var i in arr) {
      if (arr[i].shop_id == shop_id) {
        arr[i].liuyan = e.detail.value

        arr[i].icon = true
      }
    }

    this.setData({
      glistAll: arr
    })
  },
  // 清空买家留言内容
  clear: function (e) {
    var that = this
    var arr = that.data.glistAll
    var shop_id = e.target.dataset.shop_id
    for (var i in arr) {
      if (arr[i].shop_id == shop_id) {
        arr[i].liuyan = ""
        arr[i].icon = false
      }
    }
    this.setData({
      glistAll: arr
    })
  },
  //  添加新地址
  add_address: function () {
    wx.redirectTo({
      url: '../address_select/address_select?from=vr_buy_step1'
    })
  },
  //选择新地址
  address_select: function () {
    wx.redirectTo({
      url: '../address_select/address_select?from==vr_buy_step1'
    })
  },
  //点击货到付款
  pay_add: function () {
    var that = this
    var freight = 0

    if (that.data.virtual_phone == '' && that.data.is_allow_visit == 0) {
      app.show("请输入手机号码")
    } else if(that.data.realDate == '' ) {
      app.show("请选择预约时间")
    } else {
      var arr = that.data.glistAll
      for (var i in arr) {
        freight += Number(arr[i].freight)
      }
      that.setData({
        active: "",
        pay_way: 2,
        freight: freight.toFixed(2)
      })
    }

  },
  //取消
  cancel: function () {
    this.setData({
      active: "active",
	  disabled: false
    })
  },
  pay_add2: function () {
    var that = this
    var freight = 0
	
	var count_price = that.data.count_price || 0  //订单金额
	var user_money = that.data.user_money || 0 //用户余额
	
	if(parseFloat(count_price) > parseFloat(user_money)) {
		wx.showModal({
		    title: '提示',
		    content: '订单金额大于用户余额，故无法使用余额支付，请更换其他支付方式',
		    confirmText: '取消',
		    cancelText: '确定',
		    success(res) {
		    }
		  });return false;
	} else if (that.data.virtual_phone == '' && that.data.is_allow_visit == 0) {
      app.show("请输入手机号码");return false;
    } else if(that.data.realDate == '' ) {
      app.show("请选择预约时间");return false;
    } else {
      var arr = that.data.glistAll
      for (var i in arr) {
        freight += Number(arr[i].freight)
      }
      that.setData({
        active2: "",
        pay_way: 3,
        freight: freight.toFixed(2)
      })
    }
  
  },

  //取消
  cancel2: function () {
    this.setData({
      active2: "active2",
	  disabled: false
    })
  },
  pay_add3: function () {
    var that = this
    var freight = 0
  	
  	var count_price = that.data.count_price || 0 //订单金额
  	var user_recharge_card = that.data.user_recharge_card || 0 //用户卡余额
  	
  	if(parseFloat(count_price) > parseFloat(user_recharge_card)) {
  		wx.showModal({
  		    title: '提示',
  		    content: '订单金额大于用户卡余额，故无法使用卡余额支付，请更换其他支付方式',
  		    confirmText: '取消',
  		    cancelText: '确定',
  		    success(res) {
  		    }
  		  });return false;
  	} else if (that.data.virtual_phone == '' && that.data.is_allow_visit == 0) {
      app.show("请输入手机号码");return false;
    } else if(that.data.realDate == '' ) {
      app.show("请选择预约时间");return false;
    } else {
      var arr = that.data.glistAll
      for (var i in arr) {
        freight += Number(arr[i].freight)
      }
      that.setData({
        active3: "",
        pay_way: 4,
        freight: freight.toFixed(2)
      })
    }
  
  },
  
  //取消
  cancel3: function () {
    this.setData({
      active3: "active3",
  	  disabled: false
    })
  },
  //支付
  formSubmit: function (e) {

	// 获取当前实际商品数量（从页面显示获取）
	var currentGoodsNum = that.data.goods_num;

    var that = this
    var arr = that.data.glistAll
    var remarks = []
    var pay_way = that.data.pay_way
	that.setData({
	     hd: '',
	     delivery: ''
	})

    for (var i in arr) {
      remarks.push(arr[i].liuyan)
    }
	
    if (that.data.virtual_phone == '') {
      that.show("请输入手机号码")
    } else if(that.data.realDate == '' ) {
      that.show("请选择预约时间")
	} else {
      app.show('订单提交中', 'loading');
      // 获取收货地址数据
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Order&met=addVirtualOrder&typ=json&from=wap',
        method: 'GET',
        data: {
          k: that.data.k,
          u: that.data.u,
		  address_id: that.data.address_id,
		  receiver_name: that.data.user_address_contact,
		  receiver_address: that.data.user_address_area + '' + that.data.user_address_address,
		  receiver_phone: that.data.virtual_phone,
		  is_allow_visit: that.data.is_allow_visit,
		  area_code: "86",
		  buyer_phone: that.data.virtual_phone,
          goods_id: that.data.goods_id,
          goods_num: currentGoodsNum,
          pay_way_id: pay_way,
          remarks: that.data.realDate,
          wxapp: 'wxapp',
          is_discount: that.data.is_discount,
          voucher_id: that.data.voucher_id.toString(),
          redpacket_id: that.data.redpacket_id,
		  look_common_packing_list: 1,
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          
          if (res.data.status == 200) {

            if (pay_way == 2) {

              wx.redirectTo({
                url: '../order_list/order_list'
              })
            } else if (pay_way == 3) {
                that.pay_yue(res.data.data.uorder,res.data.data.order_id)
            } else if (pay_way == 4) {
                that.pay_card_yue(res.data.data.uorder,res.data.data.order_id)
            } else {
              that.pay(res.data.data.uorder,res.data.data.order_id)
            }

          } else {
            that.show("支付失败,请重新支付")
          }
        }
      })
    }
	
	
	
  },
  //微信支付接口
  pay: function (uorder_id,order_id) {
    var that = this
    var openid = wx.getStorageSync('openid');
    this.setData({disabled:true});
    wx.request({
      url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=createWXOrder&typ=json',
      method: 'GET',
      data: {
        k: that.data.k,
        u: that.data.u,
        uorder_id: uorder_id,
        openid: openid,
        trade_type: 'WXAPP'
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function (res) {
            that.show('支付成功');
            wx.request({
              url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=order_status&typ=json',
              method: 'GET',
              data: {
                k: that.data.k,
                u: that.data.u,
                order_id: uorder_id,
                buyer_id: that.data.u,
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                wx.redirectTo({
                  url: '../vr_order_detail/vr_order_detail?order_id=' + order_id
                })
              }
            })
          },
          'fail': function (res) {
            wx.redirectTo({
              url: '../order_list/order_list'
            })
          },
          'complete': function (res) {
            wx.redirectTo({
              url: '../vr_order_detail/vr_order_detail?order_id=' + order_id
            })
          }
        });
      }

    })

  },
  
  //余额支付接口
  pay_yue: function (uorder_id,order_id) {
    var that = this
    this.setData({disabled:true});
    wx.request({
      url: app.configData.paycenter.api_url + '/index.php?ctl=Info&met=checkPayWay&typ=json',
      method: 'GET',
      data: {
        k: that.data.k,
        u: that.data.u,
		card_payway: false,
		money_payway: true,
		bt_payway: false,
		online_payway: false,
		uorder_id: uorder_id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.request({
          url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=money&typ=json',
          method: 'GET',
          data: {
            k: that.data.k,
            u: that.data.u,
            trade_id: uorder_id,
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            wx.redirectTo({
              url: '../vr_order_detail/vr_order_detail?order_id=' + order_id
            })
          }
        })
      },
	  'fail': function (res) {
		  that.show("支付失败,请重新支付")
	  },
  
    })
  
  },
  //卡余额支付接口
  pay_card_yue: function (uorder_id,order_id) {
    var that = this
    this.setData({disabled:true});
    wx.request({
      url: app.configData.paycenter.api_url + '/index.php?ctl=Info&met=checkPayWay&typ=json',
      method: 'GET',
      data: {
        k: that.data.k,
        u: that.data.u,
  		card_payway: true,
  		money_payway: false,
  		bt_payway: false,
  		online_payway: false,
  		uorder_id: uorder_id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.request({
          url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=money&typ=json',
          method: 'GET',
          data: {
            k: that.data.k,
            u: that.data.u,
            trade_id: uorder_id,
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            wx.redirectTo({
              url: '../vr_order_detail/vr_order_detail?order_id=' + order_id
            })
          }
        })
      },
  	  'fail': function (res) {
  		  that.show("支付失败,请重新支付")
  	  },
  
    })
  
  },
  //加价购
  // get_addShop: function (e) {
  //   this.setData({
  //     is_add: true
  //   })
  // },
  off: function () {
    this.setData({
      is_add: false
    })
  },
  //代金券领取
  receive: function (e) {
    var that = this
    var shop_id = e.target.dataset.shop_id

  },
  //跳转到代金券页面
  store_voucher_get: function (e) {
    var that = this
    var glist = encodeURIComponent(base64.encode(JSON.stringify(e.currentTarget.dataset.info)))
    var v_price = e.currentTarget.dataset.best_voucher_price
    var shop_id = e.currentTarget.dataset.shop_id
    var voucher_ids = e.currentTarget.dataset.voucher_ids
    var keys = e.currentTarget.dataset.keys
    wx.navigateTo({
      url: '../store_voucher_get/store_voucher_get?glist=' + glist + '&count_price=' + that.data.count_price + '&v_price=' + v_price + '&shop_id=' + shop_id + '&voucher_ids=' + voucher_ids + '&keys=' + keys,
    })
  },
  //会员折扣切换
  switch1Change: function () {
    var that = this
    if (that.data.is_discount == 0) {
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirm&typ=json',
        method: 'GET',
        data: { k: that.data.k, u: that.data.u, product_id: that.data.product_id, address_id: that.data.address_id, ifcart: 1, type_wxapp: 'wxapp', is_discount: 1 },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var arr = res.data.data.glist
          var total_count = 0;
          var shop_id = [];
          var glist = res.data.data

          // 有数据的话，就遍历数据，计算总金额 和 总数量  
          if (arr.length > 0) {
            for (var i in arr) {
              var good_num = arr[i].goods;
              arr[i].icon = false
              arr[i].liuyan = ""
              shop_id.push(arr[i].shop_id)
              for (var s in good_num) {
                total_count += Number(good_num[s].sumprice);
                total_count += Number(arr[i].freight)
              }
            }
          }
          // 更新数据  
          that.setData({
            glist: glist,
            count_price: glist.order_price.toFixed(2),//注意：该变量报错时改成order_discounted_price，版本差异
            glistAll: arr,
            total: total_count,
            is_show_time: 0,
            voucher_id: [],
            is_discount: 1,
            switch1Checked: true,
            redpacket_id: 0
          });
        }
      })

    } else {

      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirm&typ=json',
        method: 'GET',
        data: { k: that.data.k, u: that.data.u, product_id: that.data.product_id, address_id: that.data.address_id, ifcart: 1, type_wxapp: 'wxapp', is_discount: 0 },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var arr = res.data.data.glist
          var total_count = 0;
          var shop_id = [];
          var voucher_id = [];
          var address = res.data.data.address
          var best_voucher = ''
          var glist = res.data.data
          var redpacket_id = 0
          // 有数据的话，就遍历数据，计算总金额 和 总数量  
          if (arr.length > 0) {
            for (var i in arr) {
              var good_num = arr[i].goods;
              arr[i].icon = false
              arr[i].liuyan = ""
              shop_id.push(arr[i].shop_id)
              for (var s in good_num) {
                total_count += Number(good_num[s].sumprice);
                total_count += Number(arr[i].freight)
              }
              //判断优惠券显示
              if (arr[i].best_voucher.length > 0) {
                arr[i].best_voucher_info = '满' + arr[i].best_voucher[0].limit + '减' + arr[i].best_voucher[0].price
              }
              //把所商品的优惠券拼成数组
              if (arr[i].best_voucher.length > 0) {
                voucher_id.push(arr[i].best_voucher[0].id)
              } else {
                voucher_id.push('')
              }

            }
          }
          //判断红包显示
          if (glist.rpt_info && glist.rpt_info.length > 0) {
            glist.best_rpt_info = '满' + glist.rpt_info[0].limit + '减' + glist.rpt_info[0].price
            redpacket_id = glist.rpt_info[0].id
          }
          // 更新数据  
          that.setData({
            glist: glist,
            count_price: glist.order_price.toFixed(2),//注意：该变量报错时改成order_discounted_price，版本差异
            glistAll: arr,
            total: total_count,
            shop_id: shop_id,
            voucher_id: voucher_id,
            redpacket_id: redpacket_id,
            switch1Checked: false,
            is_discount: 0
          });

        }
      })
    }
  },
  //跳转到平台红包页面
  red_packet: function (e) {
    var that = this
    var glist = encodeURIComponent(base64.encode(JSON.stringify(that.data.glist)))
    var redpacket_price = e.currentTarget.dataset.redpacket_price
    var redpacket_limit = e.currentTarget.dataset.redpacket_limit
    var redpacket_id = e.currentTarget.dataset.redpacket_id
    wx.navigateTo({
      url: '../red_packet_get/red_packet_get?redpacket_price=' + redpacket_price + '&redpacket_limit=' + redpacket_limit + '&redpacket_id=' + redpacket_id + '&glist=' + glist + '&count_price=' + that.data.count_price,
    })
  },

  //跳转至商品详情页面
  goToProductDetail: function (e) {
    var that = this
    var goods_id = e.currentTarget.dataset.goods_id
    wx.navigateTo({
      url: '../product_detail/product_detail?goods_id=' + goods_id
    })
  },

})